import React, { useMemo, useRef } from "react";
import { Badge } from "antd";

import { helper } from "@yaf/utils";
import { ProTable, type TableType, type IProTableRef } from "@yaf/pro-ui";
import { useThemeToken, getEnv } from "@/constants";

import { getDataAction, CreateOrEdit, getFilterItems } from './proTableDriver';
import { RespDataType } from './api';

interface ListProps {
  dictId: number;
  dictType: string;
}

const List: React.FC<ListProps> = ({ dictType }) => {
  const { themeToken } = useThemeToken();
  const proTableRef = useRef<IProTableRef>();
  const columns = useMemo(() => getColumns(), []);

  return <ProTable
    ref={proTableRef}
    dataAction={getDataAction(proTableRef, dictType)}
    rowKey={"dictCode"}
    theme={themeToken.proTableToken}
    headerProps={{
      operatorProps: {
        btnList: [
          { innerType: "create" },
          { innerType: "edit" },
          { innerType: "delete" }
        ],
        createOrEditProps: {
          modalProps: {
            width: "45%"
          },
          CreateOrEditContent: CreateOrEdit,
          getModalTitle: (rowKey) => rowKey ? "编辑字典数据" : "创建字典数据",
        },
      },
      filterProps: {
        maxWidth: "60%",
        filterItems: getFilterItems()
      }
    }}
    contentProps={{
      tableProps: {
        columns,
      }
    }}
    onError={(msg) => console.error(msg)}
  />
}

export default List;

const getColumns = () => {
  const { commonStatusList } = getEnv().globalConfig;
  const statusToInfo = helper.convertArrayToObj(commonStatusList);

  const columns: TableType.ColumnsType<RespDataType.DictDataItem> = [
    {
      title: '字典编码',
      dataIndex: 'dictCode',
    },
    {
      title: '字典标签',
      dataIndex: 'dictLabel',
    },
    {
      title: '字典键值',
      dataIndex: 'dictValue',
    },
    {
      title: '字典排序',
      dataIndex: 'dictSort',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (value) => statusToInfo[value] ? <Badge color={statusToInfo[value].color} text={statusToInfo[value].label} /> : "-",
    },
    {
      title: '备注',
      dataIndex: 'remark',
      render: (text) => text ?? "-"
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      render: (text) => text ?? "-"
    },
  ];

  return columns;
}
